package com.android.adc;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

import com.android.adc.service.IRingManipulatorService;
import com.android.adc.service.RingManipulatorService;
import com.android.adc.service.ServiceValues;

public class AmazingRingManipulatorActivity extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener
{
	private TextView lowVolumeText;
	private TextView highVolumeText;
	
	private CheckBox musicVolumeAffectedCheckBox;
	private Button startServiceButton;
    private Button stopServiceButton;
    
    private SeekBar lowVolumeValue;
    private SeekBar highVolumeValue;
    
    private ManipulatorServiceConnection connection;
    
    private Messenger serviceMessanger;
    private Messenger activityMessanger;
    
    private ActivityManager activityManager;
    
    private boolean isBinded = false;
    private int maxVolumeValue = 15;
    
    private int lowVolume = 0;
    private int highVolume = 0;
    
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        
        activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        
        activityMessanger = new Messenger(new ActivityMessageHandler());
        connection = new ManipulatorServiceConnection();
        
        setContentView(R.layout.main);
        
        lowVolumeText = (TextView)findViewById(R.id.lowVolumeValueText);
        highVolumeText = (TextView)findViewById(R.id.highVolumeValueText);
        
        startServiceButton = (Button)findViewById(R.id.startServiceButton);
        stopServiceButton = (Button)findViewById(R.id.stopServiceButton);
        musicVolumeAffectedCheckBox = (CheckBox)findViewById(R.id.isChangingMusicVolume);
        
        lowVolumeValue = (SeekBar)findViewById(R.id.lowVolumeValue);
        highVolumeValue = (SeekBar)findViewById(R.id.highVolumeValue);
        
        lowVolumeValue.setOnSeekBarChangeListener(this);
        highVolumeValue.setOnSeekBarChangeListener(this);
        
        lowVolumeValue.setMax(maxVolumeValue);
        highVolumeValue.setMax(maxVolumeValue);
        
        startServiceButton.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View v) 
			{
				 onStartClick();
			}
		});
        
        
        stopServiceButton.setOnClickListener(new OnClickListener() 
        {
			@Override
			public void onClick(View v) 
			{
				onStopClick();
			}
		});
        
        musicVolumeAffectedCheckBox.setOnCheckedChangeListener(this);
        
        checkControls();
       
    }
    
    private void checkControls()
    {
    	boolean isServiceRunning = isMyServiceRunning();
    	
    	startServiceButton.setEnabled(!isServiceRunning);
        stopServiceButton.setEnabled(isServiceRunning);
        lowVolumeValue.setEnabled(isServiceRunning);
        highVolumeValue.setEnabled(isServiceRunning);
        musicVolumeAffectedCheckBox.setEnabled(isServiceRunning);
    }
    
    @Override
    protected void onPause() 
    {
    	unBind();
    	
    	super.onPause();
    }
    
    @Override
    protected void onResume() 
    {
    	if(isMyServiceRunning())
    		bind();
    	
    	checkControls();
    	
    	super.onResume();
    }
    
    public void onStartClick()
    {
    	/* Zatrzymaj wczesniejszy serwis, jezeli jakis działal w tle */
    	//onStopClick();
    	
    	startService(getManipulatorService());
    	bind();
    	
    	checkControls();
    }
    
    public void onStopClick()
    {
    	unBind();
    	stopService(getManipulatorService());
    	
    	checkControls();
    }
    
    private void bind()
    {
    	if(isBinded)
    		return;
    	
    	isBinded = true;
    	bindService(getManipulatorService(), connection, BIND_AUTO_CREATE);
    }
    
    private void unBind()
    {
    	if(!isBinded)
    		return;

    	isBinded = false;
    	unbindService(connection);

    }
    
    private Intent getManipulatorService()
    {
    	return new Intent(AmazingRingManipulatorActivity.this, RingManipulatorService.class);
    }
    
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		if(buttonView.equals(musicVolumeAffectedCheckBox))
		{
			Message msg = Message.obtain(null, IRingManipulatorService.SET_MUSIC_AFFECTED, isChecked);
			sendMessage(msg);
		}
		
		
	}
	
	private class ActivityMessageHandler extends Handler 
	{
	    @Override
	    public void handleMessage(Message msg) 
	    {
	        switch (msg.what) 
	        {
	            case IRingManipulatorService.GET_VALUES:
	            {
	            	ServiceValues serviceValues = (ServiceValues)msg.obj;
	            	musicVolumeAffectedCheckBox.setChecked(serviceValues.isMusicAffected());
	            	
	            	maxVolumeValue = serviceValues.getMaxValue();
	            	
	            	setLowVolume(serviceValues.getLowVolume());
	            	setHighVolume(serviceValues.getHighVolume());
	            	
	            	lowVolumeValue.setMax(maxVolumeValue);
	            	highVolumeValue.setMax(maxVolumeValue);
	            	
	            	lowVolumeValue.setProgress(getLowVolume());
	            	highVolumeValue.setProgress(getHighVolume());
	            	
	            	lowVolumeText.setText("Low Volume Value: "+ (int)((100.0*getLowVolume())/maxVolumeValue)+"%");
	            	highVolumeText.setText("High Volume Value: "+ (int)((100.0*getHighVolume())/maxVolumeValue)+"%");
	            	
	                break;
	            }
	            default:
	            {
	                super.handleMessage(msg);
	            }
	        }
	    }
	}
    
    private class ManipulatorServiceConnection implements ServiceConnection
    {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) 
		{
			serviceMessanger = new Messenger(service);
			
			updateValues();	
		}

		@Override
		public void onServiceDisconnected(ComponentName name) 
		{
			serviceMessanger = null;
		}
    	
    }
    
    private void sendMessage(Message message)
    {
    	if(serviceMessanger == null)
    		return;
    	
		try 
		{
            serviceMessanger.send(message);
        } 
		catch (RemoteException e) 
        {

        }
    }

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) 
	{
		if(seekBar.equals(lowVolumeValue))
		{
			lowVolumeText.setText("Low Volume Value: "+ (int)((100.0*progress)/maxVolumeValue)+"%");
			
			changeLowVolume(progress);
			setLowVolume(progress);
		}
		else if(seekBar.equals(highVolumeValue))
		{
			highVolumeText.setText("High Volume Value: "+ (int)((100.0*progress)/maxVolumeValue)+"%");
			
			changeHighVolume(progress);
			setHighVolume(progress);
		}
		
	}
	
	public void changeLowVolume(int value)
	{
		Message msg = Message.obtain(null, IRingManipulatorService.SET_LOW_VOLUME_VALUE, value);
		sendMessage(msg);
	}
	
	public void changeHighVolume(int value)
	{
		Message msg = Message.obtain(null, IRingManipulatorService.SET_HIGH_VOLUME_VALUE, value);
		sendMessage(msg);
	}
	
	public void updateValues()
	{
		Message msg = Message.obtain(null, IRingManipulatorService.GET_VALUES);
		msg.replyTo = activityMessanger;
		
		sendMessage(msg);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub
		
	}
	
	public boolean isMyServiceRunning() 
	{
	    for (RunningServiceInfo service : activityManager.getRunningServices(Integer.MAX_VALUE)) 
	    {
	        if ("com.android.adc.service.RingManipulatorService".equals(service.service.getClassName())) {
	            return true;
	        }
	    }
	    return false;
	}

	public int getLowVolume() {
		return lowVolume;
	}

	public void setLowVolume(int lowVolume) {
		this.lowVolume = lowVolume;
	}

	public int getHighVolume() {
		return highVolume;
	}

	public void setHighVolume(int highVolume) {
		this.highVolume = highVolume;
	}
	
	

}